/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.dy.yunying.biz.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.entity.DmSearchTmplate;
import com.dy.yunying.api.entity.TemplateInfo;
import com.dy.yunying.api.req.SearchTmplateAddReq;
import com.dy.yunying.api.req.SearchTmplateEditReq;
import com.dy.yunying.biz.service.ads.DmSearchTmplateService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;


/**
 * 搜索模板表
 *
 * @author xuzilei
 * @date 2021-06-17 16:45:36
 */
@RestController
@AllArgsConstructor

@RequestMapping("/dmsearchtmplate")
@Api(value = "dmsearchtmplate", tags = "搜索模板表管理")
public class DmSearchTmplateController {
	@Resource
	private final DmSearchTmplateService dmSearchTmplateService;

	private final StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据模板名称分页查询
	 *
	 * @param name
	 * @param current
	 * @param size
	 * @return
	 */
	@ApiOperation(value = "根据模板名称分页查询", notes = "根据模板名称分页查询")
	@GetMapping("/page")
	public R getDmSearchTmplatePage(@ApiParam(value = "模板名称") @RequestParam(required = false) String name,
									@ApiParam(value = "当前页，默认1") @RequestParam(defaultValue = "1", required = false) int current,
									@ApiParam(value = "每页显示条数，默认 10") @RequestParam(defaultValue = "10", required = false) int size) {
		final String username = SecurityUtils.getUser().getUsername();
		return R.ok(dmSearchTmplateService.page(new Page<>(current, size), Wrappers.<DmSearchTmplate>lambdaQuery().eq(DmSearchTmplate::getCreateUser, username).like(StringUtils.isNotBlank(name), DmSearchTmplate::getName, name)));
	}

	/**
	 * 根据模板名查询数据列表
	 *
	 * @param name
	 * @return
	 */
	@ApiOperation(value = "根据模板名查询数据列表", notes = "根据模板名查询数据列表")
	@GetMapping("/list")
	public R getDmSearchTmplateList(@ApiParam(value = "模板名称") @RequestParam(required = false) String name) {
		final String username = SecurityUtils.getUser().getUsername();
		return R.ok(dmSearchTmplateService.list(Wrappers.<DmSearchTmplate>lambdaQuery().eq(DmSearchTmplate::getCreateUser, username).like(StringUtils.isNotBlank(name), DmSearchTmplate::getName, name)));
	}

	/**
	 * 通过id查询搜索模板表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/get/{id}")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(dmSearchTmplateService.getById(id));
	}

	/**
	 * 新增搜索模板表
	 *
	 * @param addReq 搜索模板表
	 * @return R
	 */
	@ApiOperation(value = "新增搜索模板", notes = "新增搜索模板")
	@SysLog("新增搜索模板表")
	@PostMapping("/add")
	/*@PreAuthorize("@pms.hasPermission('dm_dmsearchtmplate_add')")*/
	public R save(@RequestBody @Validated SearchTmplateAddReq addReq) {
		final PigUser user = SecurityUtils.getUser();
		if (dmSearchTmplateService.count(Wrappers.<DmSearchTmplate>lambdaQuery().eq(DmSearchTmplate::getName, addReq.getName()).eq(DmSearchTmplate::getCreateUser, user.getUsername())) > 0) {
			return R.failed(String.format("[%s]已存在", addReq.getName()));
		}
		try {
			DmSearchTmplate dmSearchTmplate = addReq.convertDmSearchTmplate(SecurityUtils.getUser().getUsername());
			dmSearchTmplateService.save(dmSearchTmplate);
			Long templateId = dmSearchTmplate.getId();
			Integer userId = user.getId();
			String info = dmSearchTmplate.getInfo();
			TemplateInfo templateInfo = JSONObject.parseObject(info, TemplateInfo.class);
			List<String> customColumn = templateInfo.getCustomColumn();
			if (CollectionUtils.isNotEmpty(customColumn)){
				stringRedisTemplate.opsForValue().set(CommonConstants.AD_ORDER_COLS_+ userId+"_"+templateId,String.join(",",customColumn));
			} else {
				stringRedisTemplate.opsForValue().set(CommonConstants.AD_ORDER_COLS_+ userId+"_"+templateId,CommonConstants.AD_DYNAMIC_NONE);
			}
			return R.ok();
		} catch (DuplicateKeyException e) {
			return R.failed(String.format("[%s]已存在", addReq.getName()));
		}
	}

	/**
	 * 修改搜索模板表
	 *
	 * @param editReq 搜索模板表
	 * @return R
	 */
	@ApiOperation(value = "修改搜索模板", notes = "修改搜索模板")
	@SysLog("修改搜索模板表")
	@PutMapping("/edit")
	/*@PreAuthorize("@pms.hasPermission('dm_dmsearchtmplate_edit')")*/
	public R updateById(@RequestBody @Validated SearchTmplateEditReq editReq) {
		DmSearchTmplate tmplate = dmSearchTmplateService.getById(editReq.getId());
		if (Objects.isNull(tmplate)) {
			return R.failed("当前模板不存在");
		}
		if (!tmplate.getCreateUser().equals(SecurityUtils.getUser().getUsername())) {
			return R.failed("无权更新当前模板");
		}
		final String username = SecurityUtils.getUser().getUsername();
		if (dmSearchTmplateService.count(Wrappers.<DmSearchTmplate>lambdaQuery().eq(DmSearchTmplate::getName, editReq.getName()).eq(DmSearchTmplate::getCreateUser, username).ne(DmSearchTmplate::getId, tmplate.getId())) > 0) {
			return R.failed(String.format("[%s]已存在", editReq.getName()));
		}
		try {
			BeanUtil.copyProperties(editReq, tmplate);
			dmSearchTmplateService.updateById(tmplate);

			Long templateId = tmplate.getId();
			Integer userId = SecurityUtils.getUser().getId();
			String info = tmplate.getInfo();
			TemplateInfo templateInfo = JSONObject.parseObject(info, TemplateInfo.class);
			List<String> customColumn = templateInfo.getCustomColumn();
			if (CollectionUtils.isNotEmpty(customColumn)){
				stringRedisTemplate.opsForValue().set(CommonConstants.AD_ORDER_COLS_+ userId+"_"+templateId,String.join(",",customColumn));
			} else {
				stringRedisTemplate.opsForValue().set(CommonConstants.AD_ORDER_COLS_+ userId+"_"+templateId,CommonConstants.AD_DYNAMIC_NONE);
			}
			return R.ok();
		} catch (DuplicateKeyException e) {
			return R.failed(String.format("[%s]已存在", editReq.getName()));
		}
	}

	/**
	 * 通过id删除搜索模板表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除搜索模板", notes = "通过id删除搜索模板")
	@SysLog("通过id删除搜索模板")
	@GetMapping("/del")
	/*@PreAuthorize("@pms.hasPermission('dm_dmsearchtmplate_del')")*/
	public R removeById(@RequestParam Long id) {
		DmSearchTmplate tmplate = dmSearchTmplateService.getById(id);
		if (Objects.isNull(tmplate)) {
			return R.failed("当前模板不存在");
		}
		if (!tmplate.getCreateUser().equals(SecurityUtils.getUser().getUsername())) {
			return R.failed("无权删除当前模板");
		}
		dmSearchTmplateService.removeById(id);
		stringRedisTemplate.delete(CommonConstants.AD_ORDER_COLS_+ SecurityUtils.getUser().getId()+"_"+id);
		return R.ok();
	}

}
